package com.example.redisdemo.task;

import com.example.redisdemo.entity.SubMessage;
import com.example.redisdemo.mapper.SubMessageMapper;
import com.example.redisdemo.util.RedisOperatingUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;

// 将redis数据放进mysql中
@Slf4j
public class RedisToMysqlTask extends QuartzJobBean {
    @Resource
    private RedisOperatingUtil redisOperatingUtil;
    @Resource
    private SubMessageMapper subMessageMapper;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 获取存储在redis中聊天记录的条数
        long messageListSize = redisOperatingUtil.listLen("subMessage");
        // 写入数据库的数据总条数
        long resultCount = 0;
        for (int i = 0; i < messageListSize; i++) {
            // 从头到尾取出链表中的元素
            SubMessage subMessage= (SubMessage) redisOperatingUtil.listPopLeftKey("subMessage");
            // 向数据库写入数据
            int result = subMessageMapper.addMessageTextInfo(subMessage);
            if (result > 0) {
                // 写入成功
                resultCount++;
            }
        }
        log.info(resultCount+ "条聊天记录，已写入数据库");
    }
}

